﻿using AutoMapper;
using B.S.RbacData.Domain;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Read.API.Applications.Commands.RBAC;
using B.S.RbacData.Read.API.Dtos;
using MediatR;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.RbacData.Read.API.Applications.CommandHandlters.RBAC
{
    /// <summary>
    /// 权限菜单命令处理
    /// </summary>
    public class GetMenuCommandhandlter : IRequestHandler<GetMenuCommand, ApiResult<List<MenuPermissionDtos>>>
    {
        private readonly IBaseRepository<RolePermissionModel> rolepermissionRep;
        private readonly IBaseRepository<PermissionModel> permissionRep;
        private readonly IMapper mapper;

        public GetMenuCommandhandlter(IBaseRepository<RolePermissionModel> rolepermissionRep, IBaseRepository<PermissionModel> permissionRep, IMapper mapper)
        {
            this.rolepermissionRep = rolepermissionRep;
            this.permissionRep = permissionRep;
            this.mapper = mapper;
        }

        public async Task<ApiResult<List<MenuPermissionDtos>>> Handle(GetMenuCommand request, CancellationToken cancellationToken)
        {
            // 获取所有角色对应的权限ID（使用并集，避免重复）
            var permissionIds = rolepermissionRep.GetAll()
                .Where(x => request.RoleIds.Contains(x.RoleId))
                .Select(x => x.PermissionId)
                .Distinct()
                .ToList();

            // 获取带权限过滤的树形结构
            var menuTree = GetTree(0, permissionIds);

            return new ApiResult<List<MenuPermissionDtos>>
            {
                code = ResultEnumCode.Ok,
                data = menuTree,
                message = "获取成功"
            };
        }


        /// <summary>
        /// 树形的递归
        /// </summary>
        /// <param name="parentId">父级Id</param>
        /// <param name="permissionIds">权限Id集合</param>
        /// <returns>返回结果</returns>
        public List<MenuPermissionDtos> GetTree(int parentId, List<int> permissionIds)
        {
            List<MenuPermissionDtos> menus = new List<MenuPermissionDtos>();
            
            // 获取当前层级的所有权限
            var permissions = permissionRep.GetAll()
                .Where(x => x.ParentId == parentId&&!x.IsDeleted)
                .ToList();

            foreach (var item in permissions)
            {
                // 获取子节点
                var children = GetTree(item.ID, permissionIds);
                
                // 如果当前节点有权限或者子节点不为空，则添加该节点
                if (permissionIds.Contains(item.ID) || children.Any())
                {
                    menus.Add(new MenuPermissionDtos()
                    {
                        ID = item.ID,
                        PermissionName = item.PermissionName,
                        URL = item.URL,
                        children = children
                    });
                }
            }

            return menus;
        }
    }
}
